package com.boot.message.netty.server;

import com.boot.message.mail.Email;
import com.boot.message.netty.server.handler.AbstractServerChannelInitializer;
import com.boot.message.netty.server.handler.BaseServerHandler;
import com.boot.message.netty.server.handler.impl.JSONServerHandler;
import com.boot.message.netty.server.handler.impl.JSONServerInitializer;
import com.boot.message.netty.server.handler.impl.StringServerHandler;
import com.boot.message.netty.server.handler.impl.StringServerInitializer;
import com.boot.message.netty.server.receiver.NettyServerReceiver;
import com.boot.message.netty.server.receiver.impl.JSONReceiver;
import com.boot.message.netty.server.receiver.impl.StringReceiver;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.channel.socket.SocketChannel;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

/**
 * @author 霜寒 <1621856595@qq.com>
 * @description netty服务端处理器配置（默认实现）
 * @date 2020/1/4 18:47
 **/

@Configuration
public class NettyServerConfig {

    @Bean
    @ConditionalOnMissingBean(BaseServerHandler.class)
    BaseServerHandler stringServerHandler() {
        return new StringServerHandler();
    }

    @Bean
    @ConditionalOnMissingBean(AbstractServerChannelInitializer.class)
    AbstractServerChannelInitializer<SocketChannel> stringServerChannelInitializer(BaseServerHandler baseServerHandler) {
        return new StringServerInitializer(baseServerHandler);
    }

    @Bean
    @ConditionalOnMissingBean(NettyServerReceiver.class)
    NettyServerReceiver stringReceiver(NettyServerProperties nettyServerProperties, AbstractServerChannelInitializer<SocketChannel> serverChannelInitializer) {
        return new StringReceiver(nettyServerProperties, serverChannelInitializer);
    }

    @Primary
    @Bean
    NettyServerReceiver jsonReceiver(NettyServerProperties nettyServerProperties, ObjectMapper om) {
        return new JSONReceiver(nettyServerProperties,
                new JSONServerInitializer(new JSONServerHandler(om, Email.class)));
    }

}
